package pattern.controller;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONUtil;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import pattern.WorkServiceTool;
import pattern.annontations.Secure;
import pattern.config.session.SessionCacheManage;
import pattern.constant.DefaultSystemConstant;
import pattern.dto.User;
import pattern.result.ResponseData;
import pattern.result.ResponseResultStatus;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author Simon
 * @date 2020-08-21
 */
@Api(tags = "虚拟Swagger接口")
@ApiSort(0)
@Controller
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@Secure(-1)
@Slf4j
public class SimulateController {

    @ApiOperation(value = "登陆")
    @PostMapping(DefaultSystemConstant.LOGIN_URL)
    public void login(@ApiParam(value = "账号") String account,
                      @ApiParam(value = "密码")String password,
                      @ApiParam(value = "验证码")String code,
                      @ApiParam(value = "邮箱登录为 email 其他情况不填")String type) {
    }

    @ApiOperation(value = "设置语言")
    @GetMapping(DefaultSystemConstant.SET_LOCAL_URL)
    public void setLocal(String local) {
    }

    @RequestMapping(value = "/")
    @ApiIgnore
    public String index() {
        return "login";
    }

    @RequestMapping(value = "/face")
    @ApiIgnore
    public String face() {
        return "face";
    }

    @ApiOperation("人脸登陆")
    @PostMapping(value = "/authentication")
    public String authentication(String account, String password, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        User user = WorkServiceTool.getUserService().findOne(account, password,null);
        if (Objects.isNull(user) || !DigestUtil.bcryptCheck(password, user.getPsw())) {
            ResponseData.sendClient(response, JSONUtil.toJsonStr(new ResponseData<>(ResponseResultStatus.WRONG_PASSWORDS)));
            return null;
        }else{
            //登陆成功
            SessionCacheManage.setSessionToken(user, request, response);
        }
        return "index";
    }
}
